import requests
from Common.api_request_data import get_session_data
import json
from Common.operate_file import read_file
from config import constant_file
import os


class HttpClient:

    def __init__(self,env:str,file_path:str):
        #获取根目录
        # self.BASIC_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

        #传的file_path需要从Common下级目录开始
        self.file_path=file_path
        #判断运行环境
        if env.upper() == 'OFFLINE':
            self.api_url=get_session_data.TempData.offline_url
        elif env.upper() == 'PRE':
            self.api_url=get_session_data.TempData.pre_url
        elif env.upper() == 'ONLINE':
            self.api_url=get_session_data.TempData.online_url
        else:
            self.api_url = get_session_data.TempData.offline_url
        # if data_type == 'TEST_INTERFACE_CASE_DATA_CSV':
        self.data_source=read_file.ReadFileData().read_csv(file_path)

    def http_request(self)-> list:
        res=[]
        res_dict= {}
        n=1
        for test_case in self.data_source:
            request_type = str(test_case['method']).upper()
            url = self.api_url + test_case['interface_path']
            params = test_case.get('Params', None)
            headers = test_case.get('Headers', None)
            body = test_case.get('para_data', None)

            if request_type == 'GET':
                response = requests.get(url, params=params, headers=headers)
            elif request_type == 'POST':
                response = requests.post(url, json=json.loads(body))
            elif request_type == 'PUT':
                response = requests.put(url, json=json.loads(body))
            elif request_type == 'DELETE':
                if body is None or body == '':
                    response = requests.delete(url)
                else:
                    response = requests.delete(url, json=json.loads(body))
            else:
                print(f"Invalid request type: {request_type}")
                continue

            res_dict['case'+str(n)]=test_case['interface_name']
            res_dict['Response'+str(n)]=f'{response.status_code} - {response.text}'
            n+=1
            res.append(res_dict)
        return res

if __name__ == '__main__':
    print(HttpClient("OFFLINE",'\operate_file\interface_list.csv').http_request())